<?php 
// +----------------------------------------------------------------------
// | CRMUU-企微SCRM是专业的企业微信第三方源码系统.
// +----------------------------------------------------------------------
// | [CRMUU] Copyright (c) 2022 http://crmuu.com All rights reserved.
// +----------------------------------------------------------------------

namespace app\wework\controller\job;

use app\BaseController;
use think\facade\Db;
use app\wework\model\BaseModel;
use app\wework\model\user\staff\StaffModel;
use app\wework\model\QyWechatApi;
use think\facade\Log;
use think\queue\Job;


/**
  * 任务类 同步群聊
  */
 class GroupJob extends BaseController
 {

 	 /**
     * fire方法是消息队列默认调用的方法
     * @param Job $job 当前的任务对象
     * @param array $data 发布任务时自定义的数据
     */
    public function fire(Job $job, array $data)
    {
     	
        $isJobDone = $this->doHelloJob($data);
        if ($isJobDone){
            $job->delete();
			Log::info("执行完毕,删除任务" . $job->attempts() . '\n');
        }else{
            if ($job->attempts() > 3){
                $job->delete();
                Log::info("超时任务删除" . $job->attempts() . '\n');
            }
        }
 		
    }

    private function doHelloJob(array $data)
    {
        $wid = $data['wid'];
        $config = Db::table('kt_wework_config')->where('wid',$wid)->find();
 		if(!$config) return true;
 		$chatList = $data['group_chat_list'];
 		foreach ($chatList as $chat) {
 			$this->syncGroup($chat,$wid);
 		}
        return true;
    }

     /**
    * 同步成员
    **/
    private function syncGroup($chat,$wid)
    {   
        $res = QyWechatApi::getExternalGroupchatDetail($chat['chat_id'],$wid);
        if($res['errcode'] != 0) return json(['code'=>'error','data'=>$id]);
        $groupChat = $res['group_chat'];
        $group = Db::table('kt_wework_group')->where('wid',$wid)->where('chat_id',$chat['chat_id'])->find();
        $groupData = [];
        if($group) $groupData['id']=$group['id'];
        $groupData['wid']=$wid;
        $groupData['chat_id']=$chat['chat_id'];
        $groupData['status']=$chat['status'];
        $groupData['name']=$groupChat['name']?:'默认群名';
        $staffid=Db::table('kt_wework_staff')->where('wid',$wid)->where('userid',$groupChat['owner'])->value('id');
        $groupData['staff_id']=$staffid;
        $groupData['owner']=$groupChat['owner'];
        $groupData['notice']=$groupChat['notice'];
        $groupData['create_time']=$groupChat['create_time'];
        $groupData['admin']=$groupChat['admin_list'];
        Db::table('kt_wework_group')->json(['admin'])->save($groupData);
        $memberData = array_map(function($member)use($wid,$chat){
            return [
                'wid'=>$wid,
                'chat_id'=>$chat['chat_id'],
                'userid'=>$member['userid'],
                'type'=>$member['type'],
                'join_time'=>$member['join_time'],
                'join_scene'=>$member['join_scene'],
                'unionid'=>$member['unionid']??'',
                'group_nickname'=>$member['group_nickname'],
                'name'=>$member['name'],
                'invitor'=>$member['invitor'],
            ];

        }, $groupChat['member_list']);
        $sql = '';
        $sql = Db::table('kt_wework_group')->json(['invitor'])->fetchSql(true)->insertAll($memberData);
        $sql .= ' ON DUPLICATE KEY UPDATE group_nickname=VALUES(group_nickname),`name`=VALUES(`name`),unionid=value(unionid)';
        Db::execute($sql);
        return json(['code'=>'success','msg'=>'成功']);
    }

 }  
